import { useAppStore } from 'src/stores/app-store';
import { boot } from 'quasar/wrappers';
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { Notify } from 'quasar';
import { apiURL } from 'src/config/env.config';
import { Result } from './typings.d';
import { QNotifyCreateOptions } from 'quasar';
import { getRouter } from 'src/router';
import { Encrypt, Decrypt, IVStr } from 'src/utils/aesUtils';
import { showToast } from 'vant';
import { RandomCode } from 'src/utils/lib';
import { RsaEncrypto } from 'src/utils/rsaUtils';
import { getUrlParam } from './paramhandler';
import CryptoJS from 'crypto-js'
import { getFingerprintId } from 'src/utils/fingerprint';
import { getModel, getOsInfo } from 'src/utils/libs';

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $axios: AxiosInstance;
  }
}

const api = axios.create({ baseURL: apiURL });

// 添加请求拦截器
api.interceptors.request.use(async (config) => {
  const { token } = useAppStore();
  // 拦截/请求自定义返回结果
  if (!config.url) {
    config.adapter = () => {
      return new Promise((resolves) => {
        resolves({ data: { status: 200 } } as any);
      });
    };
  }
  if (token) {
    config.data = {
      ...(config.data ?? {}),
      token: config.data?.token ?? token,
    };
  }
  const { camelCaseParam } = getUrlParam()
  const TempData = {...config.data || {}};
  console.log(TempData, config.url, '接口传递参数');
  const jsons = JSON.stringify(TempData);
  const randonCode = RandomCode.code(32)
  const tranDataBase = Encrypt(jsons, randonCode);
  const ciphertextBase = RsaEncrypto.encodeString(randonCode);

  const tranData = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(tranDataBase))
	const ciphertext = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(ciphertextBase))
  config.data = {
    appId: 'admin',
    version: '1.0.1',
    tranData: jsons,
    ciphertext,
  };

  const deviceid = await getFingerprintId()
  const model = await getModel()
  const  system = getOsInfo().name

  const { channelCode } = useAppStore()

  const tempCamelCaseParam = Object.fromEntries(Object.entries(camelCaseParam).map((([key, value]) => [key, encodeURI(`${value}`)])))
  console.log(tempCamelCaseParam)
  config.headers = {
    ...tempCamelCaseParam as any,
    ... channelCode ? {ch: channelCode, channelCode,} : {},
    'clientType': 'h5',
    deviceid,
    model,
    system,
  }
  config.headers['Content-Type'] = 'application/json;charset=utf-8';

  return config;
});
// 添加响应拦截器
api.interceptors.response.use((response) => {
  const data = response.data;
  if (data?.rspCode != '0001') {
    const msg = data?.rspMsg || data?.respMsg;
    if (data?.respCode == '0002') {
      getRouter().push('/');
      // window.location.href = '/login'
      return Promise.reject(new Error(msg || '系统出现错误'));
    } else {
      !(response.config as any).diyError && showToast(msg);
    }
    return Promise.reject(new Error(msg || '系统出现错误'));
  } else {
    return data;
  }
});

export const Service: <T = any>(
  config: AxiosRequestConfig & {
    diyError?: boolean;
    errorMsgPosition?: QNotifyCreateOptions['position'];
  },
) => Promise<Result<T>> = api as any;

export default boot(({ app }) => {
  app.config.globalProperties.$axios = axios;
  app.config.globalProperties.$api = api;
});
